const {getDB} = require('../db/nedbService');
const cookieParser = require('cookie-parser');

const http = require('http');

let listDb = null;
let listManageDb = null;
let userDb = null;
let likeDb = null;

let getList = function (req,res,cmd) {
    console.log("A new request for newList");
    if (listDb==null)listDb=getDB('list');
    if (listManageDb==null)listManageDb=getDB('listManage') ;

    listDb.find({},function (err,doc) {
        switch (cmd) {
            case 'new':{
                break;
            }
            default:{
                break;
            }
        }
        res.send(doc);
    })
};

let uploadList = function(req,res){
    let listInfo = req.body;

    if (listDb==null)listDb=getDB('list');
    if (listManageDb==null)listManageDb=getDB('listManage') ;
    if (userDb==null)userDb=getDB('user');

    let list = {
        title:listInfo.title,
        subtitle:listInfo.subtitle,
        author:'',
        content:listInfo.content,
        read:0,
        like:0,
        date:new Date().toLocaleString(),
        img:listInfo.img,
        label:listInfo.label,
        abstract:listInfo.abstract,
    };

    if (req.cookies==null)req.cookies=req.req.cookies;
    let {hello} = req.cookies;
    let sessionId = cookieParser.signedCookie(hello,'localhost');
    if (sessionId===undefined)res.send(false);
    userDb.find({sessionId: sessionId},function (err,doc) {
        if (doc.length>0){
            list.author = doc[0].username;
            listDb.insert(list, function (err,doc) {
                let insertDoc = doc;
                getAbstract(insertDoc._id,insertDoc.content);
                if (!err){
                    listManageDb.find({},function (err,doc) {
                        let manageList = doc[0];
                        if (doc.length===0){
                            manageList = {
                                num:1,
                                read:0,
                                like:0,
                                label:[],
                            };
                            if (manageList.label.indexOf(insertDoc.label)===-1)
                                manageList.label.push(insertDoc.label);
                            listManageDb.insert(manageList,function (err,doc) {
                                res.send(!err)
                            })
                        }else{
                            manageList.num +=1;
                            if (manageList.label.indexOf(insertDoc.label)===-1)
                                manageList.label.push(insertDoc.label);
                            listManageDb.update({num:manageList.num-1},manageList,function (err,doc) {
                                res.send(!err);
                            })
                        }
                    })
                }else res.send(false);
            })
        } else{
            return res.send(false);
        }
    }) ;
};

let updateList = function(req,res){
    let newList = req.body;

    if (listDb==null)listDb=getDB('list');
    if (listManageDb==null)listManageDb=getDB('listManage') ;
    if(likeDb==null)likeDb=getDB('like');

    let listId = newList._id;
    listDb.find({_id:listId},function (err,doc) {
        let list = doc[0];

        //更新喜欢和阅读数量
        if (list.read!==newList.read){
            updateUsr(req,list.label,true);
            listManageDb.find({},function (err,doc) {
                doc[0].read += 1;
                listManageDb.update({},doc[0],function (err,doc) {
                    //res.send(true);
                })
            })
        } else if (list.like!==newList.like){
            listManageDb.find({},function (err,doc) {
                doc[0].like += 1;
                listManageDb.update({},doc[0],function (err,doc) {
                    //res.send(true);
                })
            })
        }

        list.read = newList.read;
        list.like = newList.like;
        list.title = newList.title;
        list.subtitle = newList.subtitle;
        list.content = newList.content;

        listDb.update({_id:listId},list,function (err,doc) {
            return res.send(true);
        })
    })
};

let getTotal = function(req,res){
    if (listManageDb==null)listManageDb = getDB('listManage');
    listManageDb.find({},function (err,doc) {
        res.send(doc[0]);
    })
};

let getAbstract = function(_id,content){
    let option = {
        host:'api.bosonnlp.com',
        path:'/summary/analysis',
        method:'post',
        headers:{
            'Content-Type':'application/json',
            'X-Token':'GrZrz9Qw.31488.CbHoarnmrIbY',
        }
    };
    let body = {
        not_exceed:0,
        percentage:0.2,
        title:'',
        content:content,
    };
    let req = http.request(option,function (res) {
        //返回数据流
        let _data="";
        res.on('data', function (chunk) {
            _data+=chunk;
            listDb.find({_id:_id},function (err,doc) {
                if (doc.length>0){
                    let listInfo = doc[0];
                    listInfo.abstract = _data;
                    listDb.update({_id:_id},listInfo,function (err,doc) {
                        
                    })
                }
            })
        });
    });
    req.write(JSON.stringify(body));
    req.end();
};

let getSearchList = function(req,res){
    if (listDb==null)listDb=getDB('list');
    let labelArr = req.req.body;
    /**
     * 规定re的格式
     * re={
     *      _id:{
     *          data:{},
     *          match:0
     *      },
     *      _id...
     * }
     */
    let re={};
    listDb.find({},function (err,doc) {
        for (let i=0;i<doc.length;i++){
            let tmpArr=doc[i].label;
            for(let j=0;j<tmpArr.length;j++){
                if (labelArr.indexOf(tmpArr[j])!==-1){
                    if (re[doc[i]._id]==null){
                        re[doc[i]._id]={
                            data:doc[i],
                            match:1
                        }
                    } else{
                        re[doc[i]._id].match++;
                    }
                }
            }
        }
        updateUsr(req,labelArr,false);
        res.send(re);
    })
};

let updateUsr = function(req,labelArr,isLike){
    if (likeDb==null)likeDb=getDB('like');
    if (userDb==null)userDb=getDB('user');

    if (req.cookies==null)req.cookies=req.req.cookies;
    let {hello} = req.cookies;
    let sessionId = cookieParser.signedCookie(hello,'localhost');

    userDb.find({sessionId: sessionId},function (err,doc) {
        if (doc.length>0){
            let username = doc[0].username;
            likeDb.find({username:username},function (err,doc) {
                let like_item = {};
                if (doc.length===0) {
                    like_item = {
                        username:username,
                        like:{},
                        query:{},
                    };
                    let tmpArr = ['风景','建筑','美女','植物','动物','动漫','游戏','科技','产品','其它'];
                    for (let i=0;i<tmpArr.length;i++){
                        like_item.like[tmpArr[i]]=0;
                        like_item.query[tmpArr[i]]=0;
                    }
                }else{
                    like_item = doc[0];
                }
                let obj;
                if (isLike){
                    obj=like_item.like;
                } else{
                    obj=like_item.query;
                }
                for (let i=0;i<labelArr.length;i++){
                    let label = labelArr[i];
                    obj[label]++;
                }
                if (isLike){
                    like_item.like=obj;
                } else{
                    like_item.query=obj;
                }
                if (doc.length===0){
                    likeDb.insert(like_item,function (err,doc) {

                    })
                } else{
                    likeDb.update({username:username},like_item,function (err,doc) {

                    })
                }
            })
        }
    })
};

let getRecommendLabel = function(req,res){
    if(likeDb==null)likeDb=getDB('like');
    if (userDb==null) userDb=getDB('user');
    let {hello} = req.req.cookies;
    let sessionId = cookieParser.signedCookie(hello,'localhost');
    userDb.find({sessionId:sessionId},function (err,doc) {
        if (doc.length>0){
            let username = doc[0].username;
            likeDb.find({username:username},function (err,doc) {
                let re = {
                    like:{},
                    query:{},
                };
                if (doc.length>0){
                    re.like=doc[0].like;
                    re.query=doc[0].query;
                }else{
                    let tmpArr = ['风景','建筑','美女','植物','动物','动漫','游戏','科技','产品','其它'];
                    for (let i=0;i<tmpArr.length;i++){
                        re.like[tmpArr[i]]=0;
                        re.query[tmpArr[i]]=0;
                    }
                }
                res.send(re);
            })
        }
    })
};

module.exports.getList = getList;
module.exports.uploadList = uploadList;
module.exports.updateList = updateList;
module.exports.getTotal = getTotal;
module.exports.getSearchList = getSearchList;
module.exports.getRecommendLabel = getRecommendLabel;